package com.alone.mybatisplus.datascope.core;

import com.alone.mybatisplus.datascope.annotation.MainScope;
import com.alone.mybatisplus.datascope.conts.DataScopeModel;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

/**
 * @author Alone
 */
@Aspect
@Component
public class MainScopeContext {

    private static final ThreadLocal<DataScopeModel> CURRENT_DATASCOPE_MODEL = new InheritableThreadLocal<>();

    public static boolean needHandle(DataScopeModel model) {
        DataScopeModel current = CURRENT_DATASCOPE_MODEL.get();
        return current == null || current.equals(model);
    }

    public static DataScopeModel get() {
        return CURRENT_DATASCOPE_MODEL.get();
    }

    public static void set(DataScopeModel model) {
        CURRENT_DATASCOPE_MODEL.set(model);
    }

    public static void clear() {
        CURRENT_DATASCOPE_MODEL.remove();
    }

    @Around("@within(mainScope) || @annotation(mainScope)")
    public Object handle(ProceedingJoinPoint joinPoint, MainScope mainScope) throws Throwable {
        try {
            if (mainScope != null && MainScopeContext.get() == null) {
                MainScopeContext.set(mainScope.value());
            }
            return joinPoint.proceed();
        } finally {
            MainScopeContext.clear();
        }
    }

}